package com.iwhalecloud.citybrain.flow.platform.manager.application.utils;

import java.util.Objects;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.iwhalecloud.citybrain.flow.platform.manager.application.common.exception.CustomClientException;
import com.xxl.sso.core.conf.Conf;
import com.xxl.sso.core.login.SsoWebLoginHelper;
import com.xxl.sso.core.user.XxlSsoUser;
import lombok.extern.slf4j.Slf4j;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

@Slf4j
public class SessionUtils {

    public static XxlSsoUser getUserInfo(){
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse httpServletResponse = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        XxlSsoUser user = SsoWebLoginHelper.loginCheck(httpServletRequest, httpServletResponse);
        if (Objects.isNull(user)){
            throw new CustomClientException("用户未登录");
        }
        return user;
    }

    public   static  XxlSsoUser  getSsoUser(){
        HttpServletRequest httpServletRequest = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getRequest();
        HttpServletResponse httpServletResponse = ((ServletRequestAttributes) RequestContextHolder.getRequestAttributes()).getResponse();
        try {
            XxlSsoUser user = SsoWebLoginHelper.loginCheck(httpServletRequest, httpServletResponse);
            return user;
        } catch (Exception ex) {
            log.error("error access sso user", ex);
            return null;
        }
    }

    public static String getUserCode(){
        return getUserInfo().getUserid();
    }
}
